package commu;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class CommunicationManager {
	
	private static Map<String, List<ICommunication>> aryLstMap = Collections.synchronizedMap(new HashMap<String, List<ICommunication>>());

	/**
	 * 注册一个服务器内部消息
	 * @param key
	 * @param com
	 */
	public static void enroll(String key, ICommunication com)
	{
		if(aryLstMap.containsKey(key))
		{
			List<ICommunication> lst = aryLstMap.get(key);
			if(!lst.contains(com))//避免消息的重复注册
			{
				lst.add(com);
			}
		}
		else 
		{
			List<ICommunication> lst = new ArrayList<ICommunication>();
			lst.add(com);
			aryLstMap.put(key, lst);
		}
	}
	
	/**
	 * 注销一个服务器的内部消息
	 * @param key
	 * @param com
	 */
	public static void logout(String key, ICommunication com)
	{
		if(aryLstMap.containsKey(key))
		{
			aryLstMap.get(key).remove(com);
		}
	}
	
	/**
	 * 发送一个服务器内部消息
	 * @param key
	 * @param value
	 */
	public static void communication(String key, Object value)
	{
		if(aryLstMap.containsKey(key))
		{
			List<ICommunication> lst = aryLstMap.get(key);
			if(!lst.isEmpty())
			{
				Iterator<ICommunication> iterator = lst.iterator();
				while(iterator.hasNext())
				{
					ICommunication com = iterator.next();
					com.onCommunication(key, value);
				}
			}
		}
	}
	
}
